package com.security.demo.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.util.StringUtils;

import com.security.demo.entity.UserRoleEnum;

public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, 
			HttpServletResponse response, Authentication auth)
			throws IOException, ServletException {
		String targetUrlParameter = getTargetUrlParameter(); 
		if (isAlwaysUseDefaultTargetUrl()|| (targetUrlParameter != null 
				&& StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
			super.onAuthenticationSuccess(request, response, auth);
			return;
		}
		GrantedAuthority[] arrs = new SimpleGrantedAuthority[auth.getAuthorities().size()];
		auth.getAuthorities().toArray(arrs);
		String role = arrs[0].getAuthority().split("_")[1];
		UserRoleEnum userrole = UserRoleEnum.valueOf(role);
		if (userrole != null) {
			String targetUrl = "/" + role.toLowerCase() + "/index";
			getRedirectStrategy().sendRedirect(request, response, targetUrl); 
		}
		clearAuthenticationAttributes(request);
	}

}
